package user_logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/go-sql-driver/mysql"
	"golang.org/x/crypto/bcrypt"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewCreateUserLogic 创建用户
func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) (resp *types.UserResponse, err error) {
	if req.Username == "" {
		return &types.UserResponse{
			Code:    500,
			Message: "创建失败, 用户名不能为空"}, fmt.Errorf("username is required")
	}
	if req.Password == "" {
		return &types.UserResponse{
			Code:    500,
			Message: "创建失败, 密码不能为空"}, fmt.Errorf("password is required")
	}
	if req.Role == "" {
		return &types.UserResponse{
			Code:    500,
			Message: "创建失败, 角色信息不能为空"}, fmt.Errorf("role is required")
	}

	// 使用 bcrypt 加密密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		return nil, fmt.Errorf("failed to hash password: %v", err)
	}

	// 判断使用的数据库类型
	flag := l.svcCtx.Config.UseMysql

	var insertSQL string
	if flag {
		insertSQL = fmt.Sprintf("INSERT INTO %s (username, password, role, email, department) VALUES (?, ?, ?, ?, ?)", l.svcCtx.Config.Mysql.Tables.UserInfoTable)
	} else {
		insertSQL = fmt.Sprintf("INSERT INTO %s (username, password, role, email, department) VALUES (?, ?, ?, ?, ?)", l.svcCtx.Config.SQLite.Tables.UserInfoTable)
	}

	// 插入用户信息到数据库
	_, err = l.svcCtx.Conn.Exec(insertSQL, req.Username, string(hashedPassword), req.Role, req.Email, req.Department)
	if err != nil {
		// 检查是否是唯一约束冲突
		if flag {
			var mysqlErr *mysql.MySQLError
			if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
				return &types.UserResponse{
					Code:    500,
					Message: "用户创建失败, 用户已存在"}, fmt.Errorf("username or email already exists")
			}
		} else {
			if err.Error() == "UNIQUE constraint failed: user_info.username" || err.Error() == "UNIQUE constraint failed: user_info.email" {
				return &types.UserResponse{
					Code:    500,
					Message: "用户创建失败, 用户已存在"}, fmt.Errorf("username or email already exists")
			}
		}
		return &types.UserResponse{
			Code:    500,
			Message: "用户创建失败: " + err.Error()}, fmt.Errorf("failed to insert user: %v", err)
	}

	return &types.UserResponse{
		Code:    200,
		Message: "用户创建成功"}, nil
}
